package ro.upt.dcda.web.admin;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.jms.StreamMessage;

import ro.upt.dcda.pricezone.common.Config;
import ro.upt.dcda.pricezone.common.JMSMediator;
import ro.upt.dcda.pricezone.common.Server;
import ro.upt.dcda.pricezone.common.StoreData;
import ro.upt.dcda.pricezone.common.Config.ServerInfo;
import ro.upt.dcda.pricezone.s1.pojo.Admin;

import com.opensymphony.xwork2.ActionContext;

public class AdminNewStore {

	private String name;
	private String description;
	private String longitude;
	private String latitude;
	private List<String> servers;

	public String execute() throws Exception {
		System.out.println("Creating new store");
		Map<String, Object> session = ActionContext.getContext().getSession();
		Admin admin = (Admin) session.get("admin");
		String adminSid = (String) session.get("adminSid");
		if (admin == null || adminSid == null) {
			return "noAuth";
		}
		servers = new ArrayList<String>();
		for (ServerInfo serverInfo : Config.getServerList()) {
			servers.add(serverInfo.getName());
		}
		double x, y;
		try {
			DecimalFormat df = new DecimalFormat();
			df.setMaximumFractionDigits(10);
			x = df.parse(latitude).doubleValue();
			y = df.parse(longitude).doubleValue();
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
			return "def";
		}
		Server server = JMSMediator.getMediator().getServerByLocation(x, y);
		if (server == null) {
			System.out.println("Server is null for " + x + " " + y);
			return "def";
		}
		StreamMessage msg = server.createStreamMessage();
		msg.writeString("newStore");
		msg.writeString(name);
		msg.writeString(description);
		msg.writeDouble(y);
		msg.writeDouble(x);
		StreamMessage response = (StreamMessage) server.getResponseFor(msg, 1000);
		if (response.readInt() == 1) {
			System.out.println("New store saved");
		} else {
			System.out.println("New store not saved");
		}
		return "def";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getLongitude() {
		return longitude;
	}

	public void setLongitude(String longitude) {
		this.longitude = longitude;
	}

	public String getLatitude() {
		return latitude;
	}

	public void setLatitude(String latitude) {
		this.latitude = latitude;
	}

	public String getDefaultServers() {
		return servers.size() > 0 ? servers.get(0) : "";
	}

	public List<String> getServers() {
		return servers;
	}

	public void setServers(List<String> servers) {
		this.servers = servers;
	}

	public List<StoreData> getStores() {
		return new ArrayList<StoreData>();
	}

	public void setStores(List<StoreData> stores) {
	}
}
